package com.fzn.face.servlet;

import com.fzn.util.FaceUtil;
import com.fzn.util.ImageUtils;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class FaceController
 * @author Fanzhineng
 */
@WebServlet("/faceController")
public class FaceController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取客户端上传的图片-上传到指定的文件夹中
		File file = ImageUtils.uploadImg(request, "imgData", "upimg");
		boolean res = false;
		boolean delFlag = true;
		
		try {
			//判断是否包含人脸信息
			String faceToke = FaceUtil.detect(file);
			if(faceToke!=null) {
				// 查找是否有相识高度的人脸信息
				res = FaceUtil.search(faceToke);
				String type = request.getParameter("type");
				if("register".equals(type)) {
					if(res) {
							res = false;
					}else {
						// 添加到人脸库中
						res = FaceUtil.addFace(faceToke);
						delFlag = false;
					}
				}
			}else {
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			// 返回数据给客户端
			if(delFlag) {
				file.delete();
			}
			PrintWriter pw = response.getWriter();
			String msg = "{\"success\":"+res+"}";
			pw.write(msg);
			pw.close();
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
